<script lang="ts" setup>
    import {computed, onMounted, ref, watch} from 'vue'
    import {useRoute, useRouter} from 'vue-router'
    import {productPost, productPut, productIdGet} from '@/api'
    import {Add12Regular} from '@vicons/fluent'
    import type {OPublishShopGoodsCategoryListGetItem} from '@/typed/response'
    import type {IProductPost, IProductPut} from '@/typed/request'
    import InstallmentDetail from '@/views/console/product/components/InstallmentDetail.vue'


    const router = useRouter()

    const showInstallmentDetail = ref(false)

    interface IProps {
        show: boolean;
        data?: any;
        width?: number | string;
    }


    const contractOptions = [
        {label: '模版A', value: 'template_a'},
        {label: '模版B', value: 'template_b'},
        {label: '模版C', value: 'template_c'},
    ]

    const physicalOptions = Array.from({length: 90}, (_, i) => ({label: `${i + 1} 天`, value: i + 1}))

    // 每月固定 1-28 天
    const digitalOptions = Array.from({length: 28}, (_, i) => ({label: `${i + 1} 日`, value: i + 1}))


    const installmentOptions = [
        {label: '3期', value: 3},
        {label: '6期', value: 6},
        {label: '9期', value: 9},
        {label: '12期', value: 12},
        {label: '24期', value: 24}
    ]


    function onShowInstallmentDetail() {
        //tenantId.value = id
        showInstallmentDetail.value = true
    }


    const route = useRoute()

    const emit = defineEmits(['update:show', 'update:list'])
    const props = withDefaults(defineProps<IProps>(), {
        width: 500
    })
    // 表单数据
    const initForm: IProductPost = {
        title: '',
        subtitleTitile: '',
        price: '',
        original_price: '',
        orderPriceEdit: 1,
        payType: '10',
        deditFlag: 0,
        deditPriceRate: '',
        contractTemplate: null,
        deductionDateType: '10',
        deductionDateValue: 7,
        deductionDateValue2: '',
        installmentArr: ['3', '6', '9', '12'],
        installmentPriceArr: [],
        imageHead: '',
        status: 1,
        remark: '',
        trainingPeriod:'',
        teachingMethod:'10'
    };

    const loading = ref(false)
    const formRef = ref()
    const formModel = ref<IProductPost>({...initForm})


    const productId = route.query.id;
    const modalTitle = computed(() => {
        if (route.params?.id) {
            return '编辑商品'
        }
        return '添加商品'
    })

    const rules = {
        title: {required: true, message: '请输入分类名称', trigger: 'blur'},
        price: {required: true, message: '请输入商品价格', trigger: 'blur'},
    }


    onMounted(async () => {
        if (productId) {
            console.log('productId===', productId)
            let productObj = await getDetail();
            if (productObj) {
                if (productObj.deductionDateType === '20') {
                    productObj.deductionDateValue2 = productObj.deductionDateValue;
                    delete productObj.deductionDateValue;
                }
                productObj.price = productObj.price + '';
                formModel.value = productObj
            }
        } else {
            formModel.value = {...initForm};
        }
    })

    async function getDetail() {
        const {code, data} = await productIdGet(productId)
        if (code === 200) {
            return data;
        }
        return null;
    }

    async function onSubmit() {
        formRef.value?.validate(async (errors) => {
            if (!errors) {
                if (formModel.value.deductionDateType === '10') {
                    formModel.value.deductionDateValue = formModel.value.deductionDateValue;
                } else if (formModel.value.deductionDateType === '20') {
                    formModel.value.deductionDateValue = formModel.value.deductionDateValue2;
                }
                loading.value = true
                const {code} = productId ? await productPut(formModel.value as IProductPut) : await productPost(formModel.value as IProductPost);
                loading.value = false
                if (code === 200) {
                    window.$message.success('保存成功')
                    formModel.value = {...initForm}

                    emit('update:list')
                    emit('update:show', false)

                    router.push('/console/product/list') // 直接跳转
                }
            }
        })
    }

    function goBack() {
        router.push('/console/product/list') // 指定页面路径
    }

    const uploading = ref(false)
    const handleAvatarUpload = async (options: any) => {
        const {file, onFinish} = options
        uploading.value = true
        try {
            const formData = new FormData()
            formData.append('files', file.file)
            const {code, data} = await publishUploadFilePost(formData)
            if (code === 200 && data?.[0]) {
                formModel.value.avatar = data
                window.$message.success('上传成功')
            }
        } catch (error) {
            window.$message.error('上传失败')
        } finally {
            uploading.value = false
            onFinish()
        }
    }


</script>

<template>
    <n-layout>
        <sub-header>
            <template #left>
                {{ productId ? '编辑商品' : '添加商品' }}
            </template>
            <template #right>
                <n-button @click="goBack">
                    返回
                </n-button>
                <n-button type="primary" @click="onSubmit">
                    保存
                </n-button>
            </template>
        </sub-header>

        <n-layout class="content">
            <n-form
                    ref="formRef"
                    :model="formModel"
                    :rules="rules"
                    label-placement="left"
                    label-width="120"
            >
                <n-form-item label="商品标题" path="title">
                    <n-input v-model:value="formModel.title" placeholder="请输入商品标题"/>
                </n-form-item>
                <!-- 提示文字，单独一行 -->
                <div
                        style="
							  display: block;
							  margin-top: -15px;
							  margin-left: 120px; /* 对齐输入框内容列 */
							  background-color: rgb(255,236.8,236.8);
							  color: #ff4949;
							  padding: 16px 10px;
							  border-radius: 4px;
							  font-size: 13px;
							  line-height: 1.4;
							"
                >
                    商品命名规范：需体现培训课程、提供服务或售卖商品内容，标题不能模糊不清。不能带有分期、贷款、兼职等违规字眼！
                </div>
                <n-form-item label="商品副标题" path="subtitleTitile">
                    <n-input v-model:value="formModel.subtitleTitile" placeholder="请输入商品副标题"/>
                </n-form-item>
                <n-form-item label="商品价格" path="price">
                    <n-input v-model:value="formModel.price" placeholder="请输入商品价格"/>
                </n-form-item>
                <n-form-item label="商品原价" path="originalPrice">
                    <n-input v-model:value="formModel.originalPrice" placeholder="请输入商品原价"/>
                </n-form-item>
                <n-form-item label="培训周期" path="trainingPeriod">
                    <n-input v-model:value="formModel.trainingPeriod" placeholder="请输入培训周期 如：6个月"/>
                </n-form-item>
                <n-form-item label="授课方式" path="teachingMethod">
                    <n-radio-group v-model:value="formModel.teachingMethod">
                        <n-radio value="10">线上</n-radio>
                        <n-radio value="20">线下</n-radio>
                    </n-radio-group>
                </n-form-item>
                <n-form-item label="下单售价可编辑" path="orderPriceEdit">
                    <n-radio-group v-model:value="formModel.orderPriceEdit">
                        <n-radio :value="1">可编辑</n-radio>
                        <n-radio :value="0">不可编辑</n-radio>
                    </n-radio-group>
                </n-form-item>
                <n-form-item label="电子合同模版" path="contractTemplate">
                    <div style="display: flex; align-items: center; gap: 8px;">
                        <!-- 给下拉框一个固定或相对宽度 -->
                        <n-select
                                v-model:value="formModel.contractTemplate"
                                :options="contractOptions"
                                placeholder="请选择电子合同模版"
                                clearable
                                style="width: 500px"
                        />
                        <n-button
                                type="primary"
                                size="small"
                                :disabled="!formModel.contractTemplate"
                                @click="previewContract"
                        >
                            预览
                        </n-button>
                    </div>
                </n-form-item>
                <n-form-item label="付款方式" path="payType">
                    <n-radio-group v-model:value="formModel.payType">
                        <n-radio value="10" checked>等额分段</n-radio>
                        <n-radio value="20">一次性收款</n-radio>
                    </n-radio-group>
                </n-form-item>
                <n-form-item
                        v-if="formModel.payType == '10'"
                        label="下单违约金提示"
                        path="deditFlag"
                >
                    <n-switch
                            v-model:value="formModel.deditFlag"
                            :checked-value="1"
                            :unchecked-value="0"
                    >
                        <template #checked>启用</template>
                        <template #unchecked>停用</template>
                    </n-switch>
                </n-form-item>
                <!-- 当 Switch 开启时显示比例输入框 -->
                <n-form-item
                        v-if="formModel.deditFlag === 1"
                        label="违约金比例 (%)"
                        path="deditPriceRate"
                >
                    <n-input
                            v-model:value="formModel.deditPriceRate"
                            :min="0"
                            :max="100"
                            placeholder="请输入违约金比例"
                    />
                </n-form-item>


                <n-form-item label="扣款日" v-if="formModel.payType == '10'" path="deductionDateType">
                    <n-radio-group v-model:value="formModel.deductionDateType"
                                   style="display: flex; align-items: center; gap: 16px;">
                        <!-- 下单日顺延 -->
                        <div style="display: flex; align-items: center; gap: 8px;">
                            <n-radio value="10">下单日顺延</n-radio>
                            <n-select
                                    v-model:value="formModel.deductionDateValue"
                                    :options="physicalOptions"
                                    placeholder="请选择天数"
                                    clearable
                                    style="width: 200px"
                            />
                        </div>

                        <!-- 每月固定 -->
                        <div style="display: flex; align-items: center; gap: 8px;">
                            <n-radio value="20">每月固定</n-radio>
                            <n-select
                                    v-model:value="formModel.deductionDateValue2"
                                    :options="digitalOptions"
                                    placeholder="请选择日期"
                                    clearable
                                    style="width: 200px"
                            />
                        </div>
                    </n-radio-group>
                </n-form-item>

                <n-form-item label="支持的分期期数" v-if="formModel.payType == '10'" path="installmentArr">
                    <n-checkbox-group v-model:value="formModel.installmentArr">
                        <n-space>
                            <n-checkbox value="3">3期</n-checkbox>
                            <n-checkbox value="6">6期</n-checkbox>
                            <n-checkbox value="9">9期</n-checkbox>
                            <n-checkbox value="12">12期</n-checkbox>
                            <n-checkbox value="24">24期</n-checkbox>
                        </n-space>
                    </n-checkbox-group>
                    <div style="color: #1890ff;font-size: 12px;cursor: pointer;" @click="onShowInstallmentDetail()">
                        应收明细
                    </div>
                </n-form-item>

                <n-form-item
                        label="缩略图"
                        path="avatar"
                >
                    <n-upload
                            accept="image/*"
                            :max="1"
                            :custom-request="handleAvatarUpload"
                            :show-file-list="false"
                    >
                        <n-space vertical>
                            <n-avatar
                                    v-if="formModel.imageHead"
                                    :size="64"
                                    :src="formModel.imageHead"
                            />
                            <n-button>
                                <template #icon>
                                    <n-icon>
                                        <svg
                                                xmlns="http://www.w3.org/2000/svg"
                                                xmlns:xlink="http://www.w3.org/1999/xlink"
                                                viewBox="0 0 24 24"
                                        >
                                            <path
                                                    d="M19 7v2.99s-1.99.01-2 0V7h-3s.01-1.99 0-2h3V2h2v3h3v2h-3zm-3 4V8h-3V5H5c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-8h-3zM5 19l3-4l2 3l3-4l4 5H5z"
                                                    fill="currentColor"
                                            ></path>
                                        </svg>
                                    </n-icon>
                                </template>
                                上传缩略图
                            </n-button>
                        </n-space>
                    </n-upload>
                </n-form-item>

                <n-form-item label="付款方式" path="status">
                    <n-radio-group v-model:value="formModel.status">
                        <n-radio :value="1">上架</n-radio>
                        <n-radio :value="0">下架</n-radio>
                    </n-radio-group>
                </n-form-item>

                <n-form-item label="商品描述" path="remark">
                    <n-input
                            type="textarea"
                            v-model:value="formModel.remark"
                            placeholder="请输入商品描述，支持多行输入"
                            rows="4"
                    />
                </n-form-item>

                <n-form-item label=" ">
                    <n-space>
                        <n-button @click="goBack">返回</n-button>
                        <n-button type="primary" @click="onSubmit">保存</n-button>
                    </n-space>
                </n-form-item>

            </n-form>
        </n-layout>

        <InstallmentDetail
                v-model:show="showInstallmentDetail"
                :price="formModel.price"
                :deductionDateValue="formModel.deductionDateValue"
                :deductionDateValue2="formModel.deductionDateValue2"
                :deductionDateType="formModel.deductionDateType"
                :installmentArr="formModel.installmentArr"
                @update:list="reloadTable"
        />

    </n-layout>
</template>

<style lang="less" scoped>
    .content {
        padding: 20px;
    }
</style>
